package voldemort.store.cachestore.volderimpl;

import com.google.common.collect.Maps;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import voldemort.server.VoldemortConfig;
import voldemort.store.StorageConfiguration;
import voldemort.store.StorageEngine;
import voldemort.store.cachestore.BlockSize;
import voldemort.utils.ByteArray;
import voldemort.utils.ReflectUtils;

import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: thsieh
 * Date: Aug 16, 2010
 * Time: 4:05:38 PM
 * To change this template use File | Settings | File Templates.
 */
public class CacheStoreConfiguration implements StorageConfiguration {

    private static Log logger = LogFactory.getLog(CacheStoreConfiguration.class);

    public static final String TYPE_NAME = "cachestore";
    private VoldemortConfig config;
    private final Map<String, VoldeStore> stores = Maps.newHashMap();
    private final Object lock = new Object();



    public CacheStoreConfiguration(VoldemortConfig config) {
        this.config = config ;
    }

    public StorageEngine<ByteArray, byte[]> getStore(String name) {
        synchronized(lock) {
            VoldeStore vs = stores.get(name);
            // create a new one, when it is not existing
            if ( vs == null ) {
                // using system property to define class that implements BlockSize interface
                // command -D[store name]=[class name]
                String blockSizeName = System.getProperty(name);
                if ( blockSizeName != null ) {
                    logger.info("using BlockSize interface of "+ blockSizeName );
                    Class blockSizeClass = ReflectUtils.loadClass( blockSizeName);
                    try {
                        BlockSize blockSize = (BlockSize) blockSizeClass.newInstance() ;
                        vs = new VoldeStore<ByteArray, byte[]>(name, blockSize, config.getDataDirectory(),
                                (short) config.getNodeId());
                    } catch ( Exception ex) {
                        logger.warn("Not able to create BlockSize interface using default "+ ex.getMessage());
                        vs = new VoldeStore<ByteArray, byte[]>(name, null, config.getDataDirectory(),
                                (short) config.getNodeId());
                    }
                }
                vs = new VoldeStore<ByteArray, byte[]>(name, null, config.getDataDirectory(),
                        (short) config.getNodeId());
            }
            return vs;
        }
    }

    public String getType() {
        return TYPE_NAME;
    }

    public void close() {
    }
}
